package com.songcha.sakura.mvp.presenter

import com.songcha.sakura.bean.ComicDetailBean
import com.songcha.sakura.mvp.contract.ComicDetailContract
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import org.json.JSONObject
import javax.inject.Inject

class ComicDetailDialogPresenter @Inject constructor(
    val mModel:ComicDetailContract.Model,
    val mView:ComicDetailContract.View
 ):ComicDetailContract.Presenter{
    override fun getComicDetail(href:String) {
        Observable.create<ComicDetailBean>{
            val bean=mModel.post(JSONObject().put("href",href))
            it.onNext(bean as ComicDetailBean)
            it.onComplete()
        }
            .map(object :Function<ComicDetailBean,ComicDetailBean>{
                override fun apply(t: ComicDetailBean): ComicDetailBean {
                    t.doubanScore=mModel.getDoubanScore(t.title)
                    return t
                }

            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ComicDetailBean> {
                override fun onSubscribe(d: Disposable) {
                    mView.onLoading()
                }

                override fun onNext(t: ComicDetailBean) {
                    mView.onComicDetail(t)
                }

                override fun onError(e: Throwable) {
                    //mView.onConnectNetworkFailed()
                    mView.onLoadError(e)
                }

                override fun onComplete() {
                    mView.onLoadSuccess()
                }

            })
        //mView.onComicDetail()
    }


}